package com.jiayou.handler

import com.jiayou.message.*
import com.jiayou.message.type.DataType
import com.jiayou.tool.SerializableTool
import io.netty.channel.Channel
import io.netty.channel.ChannelHandlerContext
import io.netty.channel.SimpleChannelInboundHandler
import io.netty.channel.group.ChannelGroup
import java.io.ByteArrayInputStream
import java.io.ObjectInputStream
import java.util.concurrent.ConcurrentHashMap

/**
@author 李 双
@data   2020-11-19  12:43
@info
 */

class ServerMessageChannelHandler(
    var users: ConcurrentHashMap<OnLineMessage, Channel>,
    var channelGroup: ChannelGroup
) :
    SimpleChannelInboundHandler<ChannelMessage>() {   //设置处理器

    lateinit var id: OnLineMessage

    override fun channelRead0(ctx: ChannelHandlerContext, msg: ChannelMessage?) {
        val obj = SerializableTool.ByteArrayToObject(msg?.byteArray)
        when (msg?.dataType) {
            DataType.BINARY -> {
                println("BINARY")
            }
            DataType.OFFLINE -> {
                println("OFFLINE")
            }
            DataType.ONLINE -> {
                println("ONLINE")
                id = obj as OnLineMessage
                users[id] = ctx.channel()  //将在线用户添加进在线用户列表
                println(id)
            }
            DataType.TEXT -> {
                println("TEXT")
                println(obj as TextMessage)
            }
            DataType.HEARTBEAT -> {
                println("HEARTBEAT")
                println(obj as HeartbeatMessage)
            }
        }
    }

    override fun channelActive(ctx: ChannelHandlerContext?) {
        channelGroup.add(ctx?.channel())
        println("新增用户")
    }

    override fun channelInactive(ctx: ChannelHandlerContext?) {
        channelGroup.remove(ctx?.channel())
        users.remove(id)
        println("移除用户 $id")
    }

    override fun exceptionCaught(ctx: ChannelHandlerContext?, cause: Throwable) {
        ctx?.channel()?.close()
        println("有连接强制断开 caused by ${cause.message}")
    }
}